'''
Created on Feb 17, 2014

@author: yfrank
'''

import time
import select

from threading import Thread as Thread


class IOHandler(Thread):
    '''
    classdocs
    '''
    timeout = 0.1
    sleep_interval = 0.01


    def __init__(self, table=None):
        super(IOHandler,self).__init__()
        self.peer_table = table
        self.stopped = True

    def run(self):
        self.stopped = False
        while (not self.is_stopped()):
            self.handle_readable()
            time.sleep(IOHandler.sleep_interval)

    def stop(self):
        self.stopped = True

    def is_stopped(self):
        return self.stopped

    def send(self,buff,addr):
        peer = self.peer_table.get_peer(addr)
        if peer and peer.isOpen():
            peer.send_message(buff)
            return True
        return False


    def handle_readable(self):
        peer2socket_map = self.peer_table.get_peer2socket_map()
        read_list = peer2socket_map.keys()
        if len(read_list) == 0: return
        readable, writable, errored = select.select(read_list, [], read_list,0)

        for s in set(readable) - set(errored):
            peer = peer2socket_map[s]
            peer.recv_message()






